package com.vic.kjlink.simpletools.attachment.service;

import com.vic.kjlink.simpletools.attachment.model.Attachment;
import com.vic.kjlink.simpletools.attachment.model.HandleResult;
import org.apache.commons.io.FileUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import pers.vic.boot.base.model.BaseResponse;
import pers.vic.boot.base.vo.BooleanWithMsg;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author Vic.xu
 * @description:
 * @date: 2021/9/16 0016 9:30
 */
@Service
public class AttachmentService {


    String SELECT = "select a.id , a.file_name as fileName, a.original_file_name as originalFilename, a.file_path AS filePath, a.file_source AS fileSource,a.file_size as fileSize "
            + " from t_stl_s_attachment a  where 1= 1 ";
    String count = "select count(*) from t_stl_s_attachment a  where 1= 1 ";
    @Resource
    private JdbcTemplate jdbcTemplate;


    /**
     * 查询附件列表
     */
    public List<Attachment> list(String sql) {
        sql = SELECT + sql;
        List<Attachment> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Attachment>(Attachment.class));
        return list;
    }

    /**
     * 检测sql
     * @param sql
     * @return
     */
    public BaseResponse<String> check(String sql) {
        sql = count + sql;
        try {
            int count = jdbcTemplate.queryForObject(sql, Integer.class);
            String msg = "本sql查询出的结果数目为:" + count + " 条";
            if (count > 1000) {
                msg = msg + ", 数目较多，处理时间较长，请谨慎处理。";
            }
            BaseResponse<String> success = BaseResponse.success();
            success.setMsg(msg);
            return success;
        } catch (Exception ex) {
            String msg = "错误信息：\n" + ex.getMessage();
            return BaseResponse.error(msg);
        }

    }

    /**
     * 把附件copy到对应的文件下
     * @param attachment
     * @param target
     * @return
     */
    public BooleanWithMsg copy(Attachment attachment, String target, HandleResult repeatFile) {
        String path = attachment.getFilePath();
        if (!StringUtils.hasText(path)) {
            return BooleanWithMsg.fail(buildDesc(attachment, "路径为空"));
        }
        String originalFilename = attachment.getOriginalFilename();
        if (!StringUtils.hasText(originalFilename)) {
            return BooleanWithMsg.fail(buildDesc(attachment, "原文件名为空"));
        }

        File source = new File(path);
        if (!source.exists()) {
            return BooleanWithMsg.fail(buildDesc(attachment, "源文件不存在"));
        }

        try {
            //复制文件
            originalFilename = repeatFile.addFileSeq(originalFilename, source.getName());
            FileUtils.copyFile(source, new File(target, originalFilename));
            repeatFile.addSuccessNumber();
        } catch (IOException e) {
            return BooleanWithMsg.fail(buildDesc(attachment, e.getMessage()));
        }
        return BooleanWithMsg.success(buildDesc(attachment, null));
    }

    /**
     * 构件本条附件的操作结果
     * @param attachment
     * @param msg 有msg的时候表示操作失败
     * @return
     */
    private String buildDesc(Attachment attachment, String msg) {
        String flag = StringUtils.hasText(msg) ? "<strong style='color:red;'>操作失败：</strong>" + msg : "操作成功!";

        StringBuilder sb = new StringBuilder();
        sb.append("id: [").append(attachment.getId()).append("], ")
                .append("原文件名：[").append(attachment.getOriginalFilename()).append("], ")
                .append("文件大小：[").append(attachment.getFileSize()).append("], ")
                .append(flag);
        return sb.toString();
    }

    /**
     * ajax 处理附件
     * @param sql
     * @param target
     * @return
     */
    public BaseResponse handle(String sql, String target) {
        List<Attachment> list = this.list(sql);
        if (CollectionUtils.isEmpty(list)) {
            return BaseResponse.error("没有需要处理的附件");
        }
        HandleResult handleResult = new HandleResult(list);
        for (Attachment attachment : list) {
            this.copy(attachment, target, handleResult);
        }
        return BaseResponse.success().setMsg(handleResult.getDesc());
    }
}
